package com.lc.lcapiclientsdk.client;

import cn.hutool.core.util.RandomUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONUtil;
import com.lc.lcapiclientsdk.model.User;

import java.util.HashMap;
import java.util.Map;

import static com.lc.lcapiclientsdk.util.SignUtil.getsign;


/**
 * 功能：调用第三方接口的客户端
 * 作者：lc
 * 日期：2024/10/10 18:05
 */
public class LcApiClient {
    // 网关地址
    private static final String GATEWAY_HOST = "http://localhost:8731";
    private String accessKey;
    private String secretKey;

    public LcApiClient(String accessKey, String secretKey) {
        this.accessKey = accessKey;
        this.secretKey = secretKey;
    }

    // get
    public String getName(String name) {
        // 可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap();
        paramMap.put("name", name);
        String result3 = HttpUtil.get(GATEWAY_HOST + "/api/name/", paramMap);
        System.out.println(result3);
        return result3;
    }

    // post
    public String postName(String name) {
        // 可以单独传入http参数，这样参数会自动做URL编码，拼接在URL中
        HashMap<String, Object> paramMap = new HashMap();
        paramMap.put("name", name);
        String result3 = HttpUtil.post(GATEWAY_HOST + "/api/name/", paramMap);
        System.out.println(result3);
        return result3;
    }

    // restful风格
    public String postNameByUser(User user) {
        String json = JSONUtil.toJsonStr(user);
        HttpResponse httpResponse = HttpRequest.post(GATEWAY_HOST + "/api/name/postByUser")
                .addHeaders(getHeards(json))
                .body(json)
                .execute();
        String result = httpResponse.body();
        System.out.println(httpResponse.getStatus());
        System.out.println(result);
        return result;
    }
    public Map<String, String> getHeards(String body) {
        Map<String,String> heards = new HashMap();
        heards.put("accessKey", accessKey);
        // heards.put("secretKey",secretKey);
        heards.put("nonce", RandomUtil.randomNumbers(4));
        heards.put("body", body);
        heards.put("timestamp", String.valueOf(System.currentTimeMillis() / 1000));
        heards.put("sign", getsign(body, secretKey));
        return heards;
    }

}
